/**
 * UI 工具函数 - Toast 和 Modal 便捷使用方法
 */

import { toast } from '../stores/toastStore';
import { modal } from '../stores/modalStore';

// =====================================================
// Toast 消息提示工具函数
// =====================================================

/**
 * 成功操作提示
 */
export const showSuccess = (message: string, title: string = '成功') => {
  toast.success(message, { title });
};

/**
 * 错误提示
 */
export const showError = (message: string, title: string = '错误') => {
  toast.error(message, { title });
};

/**
 * 警告提示
 */
export const showWarning = (message: string, title: string = '警告') => {
  toast.warning(message, { title });
};

/**
 * 信息提示
 */
export const showInfo = (message: string, title: string = '信息') => {
  toast.info(message, { title });
};

/**
 * API 操作反馈
 */
export const handleApiResponse = {
  success: (action: string = '操作') => {
    showSuccess(`${action}成功完成`);
  },
  error: (error: unknown, action: string = '操作') => {
    let message = `${action}失败`;
    if (error && typeof error === 'object') {
      if ('message' in error && typeof error.message === 'string') {
        message = error.message;
      } else if (
        'response' in error &&
        error.response &&
        typeof error.response === 'object' &&
        'data' in error.response &&
        error.response.data &&
        typeof error.response.data === 'object' &&
        'message' in error.response.data &&
        typeof error.response.data.message === 'string'
      ) {
        message = error.response.data.message;
      }
    }
    showError(message);
  },
};

// =====================================================
// Modal 确认框工具函数
// =====================================================

/**
 * 删除确认
 */
export const confirmDelete = (itemName: string, onConfirm: () => void | Promise<void>) => {
  modal.warning({
    title: '确认删除',
    content: `您确定要删除「${itemName}」吗？\n\n此操作无法撤销。`,
    confirmText: '删除',
    cancelText: '取消',
    onConfirm: async () => {
      try {
        await onConfirm();
        showSuccess('删除成功');
      } catch (error) {
        handleApiResponse.error(error, '删除');
      }
    },
  });
};

/**
 * 保存确认
 */
export const confirmSave = (onConfirm: () => void | Promise<void>, hasChanges: boolean = true) => {
  if (!hasChanges) {
    showInfo('没有需要保存的更改');
    return;
  }

  modal.confirm({
    title: '保存更改',
    content: '确定要保存当前的更改吗？',
    confirmText: '保存',
    cancelText: '取消',
    onConfirm: async () => {
      try {
        await onConfirm();
        showSuccess('保存成功');
      } catch (error) {
        handleApiResponse.error(error, '保存');
      }
    },
  });
};

/**
 * 退出确认（有未保存更改时）
 */
export const confirmExit = (onConfirm: () => void, hasUnsavedChanges: boolean = false) => {
  if (!hasUnsavedChanges) {
    onConfirm();
    return;
  }

  modal.warning({
    title: '确认退出',
    content: '您有未保存的更改，确定要退出吗？\n\n未保存的更改将会丢失。',
    confirmText: '退出',
    cancelText: '取消',
    onConfirm,
  });
};

/**
 * 重置确认
 */
export const confirmReset = (
  onConfirm: () => void | Promise<void>,
  message: string = '所有更改将恢复到初始状态'
) => {
  modal.warning({
    title: '确认重置',
    content: `确定要重置吗？\n\n${message}。`,
    confirmText: '重置',
    cancelText: '取消',
    onConfirm: async () => {
      try {
        await onConfirm();
        showSuccess('重置成功');
      } catch (error) {
        handleApiResponse.error(error, '重置');
      }
    },
  });
};

/**
 * 通用异步操作确认
 */
export const confirmAsyncAction = (
  title: string,
  content: string,
  action: () => Promise<void>,
  successMessage?: string,
  confirmText: string = '确认'
) => {
  modal.confirm({
    title,
    content,
    confirmText,
    cancelText: '取消',
    onConfirm: async () => {
      try {
        await action();
        if (successMessage) {
          showSuccess(successMessage);
        }
      } catch (error) {
        handleApiResponse.error(error, '操作');
      }
    },
  });
};

// =====================================================
// 表单验证提示工具
// =====================================================

/**
 * 表单验证失败提示
 */
export const showValidationError = (errors: { [key: string]: string }) => {
  const errorMessages = Object.values(errors).join('\n');
  showError(`表单验证失败：\n${errorMessages}`, '验证错误');
};

/**
 * 必填字段提示
 */
export const showRequiredFieldError = (fieldName: string) => {
  showError(`请填写${fieldName}`, '必填字段');
};

// =====================================================
// 加载状态提示
// =====================================================

/**
 * 显示加载提示 (返回一个 close 函数)
 */
export const showLoading = (message: string = '加载中...') => {
  toast.info(message, {
    duration: 0, // 不自动关闭
    title: '请稍候',
  });

  return () => {
    // TODO: 需要在 toastStore 中添加 removeToast 方法的导出
    // 暂时不返回关闭函数，直接让用户手动关闭
  };
};
